import React, { Component } from 'react';
import { Modal } from 'choerodon-ui';
import { Form, TextField, DataSet } from 'choerodon-ui/pro';
import Record from 'choerodon-ui/pro/lib/data-set/Record';

interface ModalProps {
  dataSet: DataSet;
  record: Record;
  onOk: () => any;
}

class UserEditModal extends Component<ModalProps, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      visible: false,
    };
  }

  /**
   * Modal显示时，根据情况设置表单数据
   */
  showModelHandler = (e: any) => {
    const { dataSet, record } = this.props;
    if (e) e.stopPropagation();
    if (record && record.toData) {
     // eslint-disable-next-line no-unused-expressions
     dataSet.current?.set(record.toData());
    } else {
      // eslint-disable-next-line no-unused-expressions
     dataSet.current?.set({name: '', email: '', website: ''});
    }
    this.setState({
      visible: true,
    });
  };

  hideModelHandler = () => {
    this.setState({
      visible: false,
    });
  };

  okHandler = async () => {
    const { onOk, dataSet } = this.props;
    const valid = dataSet.validate();
    if (valid) {
      await dataSet.submit();
      onOk();
      this.hideModelHandler();
    }
  };

  render() {
    const { children, dataSet } = this.props;

    return (
      <span>
        <span onClick={this.showModelHandler}>{children}</span>
        <Modal
          title="Edit User"
          visible={this.state.visible}
          onOk={this.okHandler}
          onCancel={this.hideModelHandler}
        >
          <Form dataSet={dataSet} onSubmit={this.okHandler}>
            <TextField name="name" />
            <TextField name="email" />
            <TextField name="website" />
          </Form>
        </Modal>
      </span>
    );
  }
}

export default UserEditModal;
